package org.example.common.security.service;

import cn.hutool.core.lang.UUID;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.example.common.core.constants.CacheConstants;
import org.example.common.core.constants.JwtConstants;
import org.example.common.redis.service.RedisService;
import org.example.common.core.model.LoginUser;
import org.example.common.core.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author : [Pashm]
 * @version : [v1.0]
 * 操作用户登录Token的方法
 */
@Service
@Slf4j
public class TokenService {

    @Autowired
    private RedisService redisService;

    public String createToken(Long userId, String secret, Integer identity, String nickname, String headImage){

        Map<String, Object> claims = new HashMap<>();
        String userKey = UUID.fastUUID().toString();
        claims.put(JwtConstants.LOGIN_USER_ID,userId);
        claims.put(JwtConstants.LOGIN_USER_KEY, userKey);
        String token = JwtUtils.createToken(claims, secret);

//          第三方机制中存储敏感信息   redis 表明用户身份字段    identity  1  表示普通用户  2 表示管理员用户  对象
//          key 必须保证唯一 便于维护  统一前缀 logintoken:userId 使用String类型存储

        String tokenKey =getTokenKey(userKey);
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickname);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey,loginUser, CacheConstants.EXP , TimeUnit.MINUTES);

        return token;
    }
    //实际上延长token的有效时间，就是延长redis当中存储的用于用户身份验证的敏感信息的有效时间

    //在身份验证通过之后，并且在请求到达controller层之前
    public void extendToken(Claims claims){
//        Claims claims ;
//        try {
//            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息
//            if (claims == null) {
//                log.error("解析token:{ }出现异常,",token);
//               return;
//            }
//        } catch (Exception e) {
//            log.error("解析token:{ }出现异常,", token, e);
//           return;
//        }
//        String userKey = JwtUtils.getUserKey(claims);
        String userKey = getUserKey(claims);
        if(userKey == null){
            return;
        }
        String tokenKey = getTokenKey(userKey);

        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if(expire != null && expire < CacheConstants.REFRESH_TIME){
            redisService.expire(tokenKey, CacheConstants.EXP, TimeUnit.MINUTES);
        }

    }

    private String getTokenKey(String userKey){
        return  CacheConstants.LOGIN_TOKEN_KEY + userKey;
    }

    public LoginUser getLoginUser(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if(userKey == null){
            return null;
        }
        return redisService.getCacheObject(getTokenKey(userKey), LoginUser.class);
    }
    public boolean deleteLoginUser(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if(userKey == null){
            return false;
        }
        return redisService.deleteObject(getTokenKey(userKey));
    }

    public Long getUserId(Claims claims){
        if (claims == null) return null;
        return Long.valueOf(JwtUtils.getUserId(claims));
    }

    public static Claims getClaims(String token, String secret) {
        Claims claims ;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息
            if (claims == null) {
                log.error("解析token:{ }出现异常,", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token:{ }出现异常,", token, e);
            return null;
        }
        return claims;
    }
    public String getUserKey(Claims claims){
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims);
    }


    private String getUserKey(String token, String secret){
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims);
    }


    public void refreshLoginUser(String nickName, String headImage, String userKey) {
        String tokenKey = getTokenKey(userKey);
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser);
    }
}
